import { ref,reactive } from 'vue'
import {logout,updatepassword} from '~/api/manager'
import {showModel,toast} from '~/composables/util'
import { useRouter } from "vue-router"
import {useStore} from 'vuex'


export function useRepassword(){
    
const router = useRouter()
const store = useStore()

    const formDrawerRef = ref(null)
    const form = reactive({
        oldpassword: '',
        password: '',
        repassword: '',
    })
    // 声明一个对象
    const rules = {
        oldpassword: [
            //每一条单独验证规则都是一个对象
            {
                required: true, //表示此input是必填的
                message: '旧密码不能为空',
                trigger: 'blur' //触发事件-->失去焦点
            }
        ], //数组：多条验证规则
        password: [
            {
                required: true, //表示此input是必填的
                message: '新密码不能为空',
                trigger: 'blur' //触发事件-->失去焦点
            }
        ],
        repassword: [
            {
                required: true, //表示此input是必填的
                message: '确认密码不能为空',
                trigger: 'blur' //触发事件-->失去焦点formDrawerRef
            }
        ],
    }

    // ref变成响应式方便获取节点
    const formRef = ref(null)
    // 防止重复加载
    const loading = ref(false)
    const onSubmit = () => {
        formRef.value.validate((valid) => {
            //会得到input表单中是否有值的true或者false
            if (!valid) {
                return false
            }
            loading.value = true
            updatepassword(form)
                .then(res => {
                    toast("修改密码成功，请重新登录")
                    store.dispatch("/login")
                })
                .finally(() => {
                    loading.value = fal
                })
        })
    }
    const openRePasswordForm = ()=>formDrawerRef.value.open()
    return{
        formDrawerRef,
        form,
        rules,
        formRef,
        loading,
        onSubmit,
        openRePasswordForm,
    }
}

export function useLogout() {
    const router = useRouter()
    const store = useStore()
    function handleLogout() {
        showModel('是否要退出登录？').then(res => {
            logout()
                // 不管退出成功还是失败都执行
                .finally(() => {

                    store.dispatch("logout")
                    //通过userRouter的push()方法进行登录页的跳转
                    router.push('/login')
                    // 提示退出成功
                    toast('退出成功')
                })
        })


    }
    return {
        handleLogout
    }
}